#' ---
#' title: "Replication Adaptive Parties Appendix"
#' author: "Lukas Stoetzer & Tarik Abou-Chadi"
#' date: "23 February 2020"
#' ---

#+ start, echo=FALSE, include=FALSE

  # Own Functions
    source("fun_panel.R")
  
  # Load Data
    load("pty_dat_mat.Rdata")
    load("pty_dat_wweights.Rdata")
    load("pty_dat_ww_dyd.RData")
    DT$year <- strtrim(DT$date,4)
  
  # Libraries
    library(dplyr)
    library(alluvial)
    library(xtable)
    library(tidyverse)
    library(ggplot2)
    library(reshape2)
    library(plm)
    library(MASS)
    library(texreg)

  # Create plm Dataset
    DT$year <- strtrim(DT$date,4)
    pd <- pdata.frame(DT, index = c("party","elec_id"))
    
#' ## A  Cases Included in the Analysis
#+ cases, echo=FALSE, results='asis'
  
  # Drop Cases with error in Transions
    DT <- filter(DT, !(countryname == "United Kingdom" & edate == "07/06/2001"),
             !(countryname == "Denmark" & date == "200502"),
             !(countryname == "Ireland" & date == "201102"),
             !(party == 51421 & date == 198306))
  
  # Information about number of uniwu parties and elections
    DT %>% 
      summarise(
        Number_Parties = length(unique(party)),
        Number_Elections = length(unique(edate))) 
  
  
  # Create Table with Election, Cases under Study
    table_with_cases <- DT %>% 
      group_by(countryname,edate) %>% 
      summarise(
        Number_Parties = n(),
        Parties = paste(iconv(partyname, "UTF-8", "UTF-8",sub=''), collapse=", ")
        # , Study = NA
      ) 
  
  # Save as Latex table
    colnames(table_with_cases) <- c("Country","Elec. Date","Num","Party Names")
    print(xtable(table_with_cases,caption = "Elections and Parties included in the Analysis"), comment=FALSE,scalebox = 0.5)
 
    
    
    
#' ## B Statistical Model and Measurement
#' ### B.2 Example of Voter Transitions
#+ Riverplot, echo=FALSE, message=FALSE, fig.width=12, fig.height=12
  
  # Case 1: Germany 2009
      df_alluvil <- filter(TRANS,edate_t2=="27/09/2009",countryname_t2=="Germany") %>%
                      dplyr::select(partyabbrev_t1,partyabbrev_t2,N_tab, tranfers) %>% 
                      rename("Election2005" = partyabbrev_t1,
                             "Election2009" = partyabbrev_t2) %>%
                      droplevels() %>%
                      mutate("Election2005" = fct_relevel(Election2005,"CDU/CSU","FDP","SDT","90/Greens","LINKE"),
                             "Election2009" = fct_relevel(Election2009,"CDU/CSU","FDP","SDT","90/Greens","LINKE"))
      
      alluvial(df_alluvil[,1:2], freq=df_alluvil$N_tab,
               col=ifelse(df_alluvil$tranfers > 0.05 , "red", "grey"),
               cex = 2,cex.axis = 2,alpha = ifelse(df_alluvil$tranfers>0.05, 0.9, 0.7),
               layer = df_alluvil$tranfers< 0.05
              )
  
      
  # Case 2: Netherlands 2006
      df_alluvil <- filter(TRANS,date_t2=="200611",countryname_t2=="Netherlands") %>%
        dplyr::select(partyabbrev_t1,partyabbrev_t2,N_tab, tranfers) %>% 
        rename("Election2003" = partyabbrev_t1,
               "Election2006" = partyabbrev_t2) %>%
        droplevels() %>%
        mutate("Election2003" = fct_relevel(Election2003,"CU","VVD","GL","CDA","PvdA","SP"),
               "Election2006" = fct_relevel(Election2006,"CU","VVD","GL","CDA","PvdA","SP"))
  
      alluvial(df_alluvil[,1:2], freq=df_alluvil$N_tab,
               col=ifelse(df_alluvil$tranfers > 0.03 , "red", "grey"),
               cex = 2,cex.axis = 2,alpha = ifelse(df_alluvil$tranfers>0.03, 0.9, 0.7)
               , layer = df_alluvil$tranfers< 0.03
      )
      
      
#' ### B.4 Validation of Voter Transitions
#+ Corr, echo=FALSE
      
  # Function aggreagte estimated transtions from output object =====
  aggretTrans <- function(dat_trans){
        
    # Use dpylr to summarise by multiple groups
    require(dplyr)
      
    # aggreagte transfers country party and election
      agg_trans <- dat_trans %>% 
      group_by(country_t2, date_t2, t2) %>%
      dplyr::summarise(
        trans_loss = sum(tranfers * (pervote_lag_t2/100)),
        loss = mean((pervote_t2-pervote_lag_t2)/100)
      )
        
    # Return 
    return(agg_trans)
  }
      
  # Prepare Data
  df <- TRANS %>% 
     filter(!(countryname_t2 == "United Kingdom" & edate_t2 == "07/06/2001"),
            !(countryname_t2 == "Denmark" & date_t2 == "200502"),
             !(countryname_t2 == "Ireland" & date_t2 == "201102"),
             !(t2 == 51421 & date_t2 == 198306)) %>%
      filter(t2 != t1) %>%
      aggretTrans() %>%
      na.omit()
  
  # Figure
  ggplot(df,aes(trans_loss,loss)) + 
    geom_smooth(method="lm") + 
    ylab("Vote Difference calulated from Transitions in Survey") +
    xlab("Vote Difference calulated from Results") +
    geom_point(alpha=0.7) + 
    theme_minimal()
    

    
#' ### B.5 Distribution of Net Transfers
#+ NetTrans, echo=FALSE, fig.width=10, fig.height=6
  
  # Histogram 
  ggplot(DTDyd) + 
    geom_histogram(aes(wn, y =..density..), binwidth = 0.05) + 
    facet_wrap(~ countryname) +
    theme_minimal() + xlab("Net Voter Transitions") + ylab("Density")


#' ## C Additional Material Main Results    
#' ### C.1 Marginal Effect Plot
#+ MeEff, echo=FALSE
  
  K <- 3
  cutoffs <- c(0,0.33,1)
  qt <- quantile(pd$pervote_diff_lag_rel,cutoffs,na.rm=T)
  
  pd$pervote_diff_lag_cut_k <-  cut(x = pd$pervote_diff_lag_rel, qt)
  
  m4 <- plm(rile ~ -1 +  rile_lag + wlp_rile *pervote_diff_lag_cut_k +
              +  countryname + avg_rile_shift_lag,
            model="pooling", data=pd)
  
  direct_sel <- match("wlp_rile",names(coef(m4)))
  inter_sel <- grep("wlp_rile\\:",names(coef(m4)),value = T)
  
  
  # Point Estimates
  direct_eff <- coef(m4)[direct_sel]
  inter_eff <- coef(m4)[inter_sel]
  
  # S.E. 
  direct_se <- sqrt(vcov(m4)[direct_sel,direct_sel])
  inter_se <- sqrt(vcov(m4)[direct_sel,direct_sel] + diag(vcov(m4))[inter_sel] + 2*vcov(m4)[inter_sel,direct_sel])
  
  pt_est <- c(direct_eff, direct_eff + inter_eff)
  se_est <- c(direct_se,inter_se)
  
  cutoff_frmt <- round(cutoffs*100)
  Quantiles <- paste(cutoff_frmt[-K],"% - ",cutoff_frmt[-1], "%",sep="")
  
  median_cut <- sapply(2:length(cutoffs), function(i)  (cutoffs[i]  + cutoffs[i-1])/2 )
  pos_me <- quantile(pd$pervote_diff_lag_rel,median_cut,na.rm=T)
  
  df <- data.frame("point_est"=pt_est, "sd_est"=se_est, 
                   "ci.low" = qnorm(0.005,pt_est,se_est), "ci.low2" = qnorm(0.025,pt_est,se_est),
                   "ci.high" = qnorm(0.995,pt_est,se_est), "ci.high2" = qnorm(0.975,pt_est,se_est),
                   "mean_value" = pos_me,
                   "cutoff_label" = as.factor(Quantiles)
  )
  
  levels(df$cutoff_label) <- c("Party lost more than 5.8%", "Party lost less than 5.8% or won votes")
  
  ggplot(df) + 
    geom_pointrange(aes(x=factor(1),y=point_est, ymin=ci.low2,ymax=ci.high2,group=cutoff_label), size=2) +
    geom_pointrange(aes(x=factor(1),y=point_est, ymin=ci.low,ymax=ci.high,group=cutoff_label), size=1.5) +
    coord_flip() +facet_wrap(~cutoff_label, ncol=1) +
    geom_hline(yintercept = 0, col="red", alpha=0.3) +
    ylab("Marginal Effect of Spatial Lag on Party Position") + xlab("") +
    theme_minimal() +
    theme(axis.text=element_text(size=18, colour="black"),
          axis.title=element_text(size=18),
          axis.text.y=element_blank(),
          strip.text.x = element_text(size = 18)) 
  
#' ### C.2Multiple Party Competition
#+ mparty, echo=FALSE
  
  
  # Model 
  pd$pervote_diff_lag_cut <-  cut(x = pd$pervote_diff_lag_rel, quantile(pd$pervote_diff_lag_rel,c(0,.33,1),na.rm=T))
  levels(pd$pervote_diff_lag_cut)  <- c("low","high")
  m3 <-    plm(rile ~ 1 +  rile_lag + wlp_rile*pervote_diff_lag_cut  + countryname + avg_rile_shift_lag, 
               model = "pooling",
               data=pd)
  
  # simulation
  S1 <- mvrnorm(10000,coef(m3),vcov(m3))
  
  # Marginal Effect of Party Position B on Party Position A
  
  # Create Different Scenarios for movement of other party and transtiions
  matS <- S1[,c("wlp_rile","wlp_rile:pervote_diff_lag_cuthigh")]
  
  # Get Scenarios
  other_pty_lr <- rbind(c(25,-25),c(25,25))
  voter_transtions <- c(0.2)
  Xlr <- expand.grid(apply(other_pty_lr*voter_transtions,1,sum), c(1,0))
  Xlr$Var2 <- Xlr$Var1 * Xlr$Var2
  
  
  # Calculate Expected Values
  evlr <- matS %*% t(Xlr)
  evlr_qi <- t(apply(evlr,2,quantile,c(0.01,0.025,0.5,0.975,0.99)))
  
  
  # Preapre Data-frame
  n_trans <- length(voter_transtions)
  lab_y <- paste(100*as.numeric(voter_transtions), "% net transfers A to B", sep="")
  lab_vl <- c("Party A lost less than 5.8% or won votes","Party A lost more than 5.8%")
  model <- c(rep("Left-Right Shift",length(voter_transtions)))
  vote_loss <- as.factor(sort(rep(lab_vl,length(voter_transtions))))
  df <- data.frame(cbind(evlr_qi,voter_transtions),"vote_loss" = vote_loss,"time"="Election","party"="Party A")
  names(df) <- c("low2","low","mid","high","high2","voter_transtions","vote_loss","time","party")
  df$loss <- lab_y
  df$parties <- c(rep("Party B & C are on opposite side of Party A \n 15% net transfers A to B and C",2*n_trans) ,   
                  rep("Party B & C are on the same side of Party A \n 15% net transfers A to B and C",2*n_trans))
  
  
  
  df_other_parties <- dplyr::select(df, vote_loss, parties, loss)
  df_othpart <- rbind(df_other_parties,df_other_parties)
  df_othpart$party <- c(rep("Party B",4),rep("Party C",4))
  df_othpart$mid <- c(25,25,25,25,-25,-25,25,25)
  

  df$party <- relevel(df$party,"Party A")
  
  df <- filter(df,vote_loss=="Party A lost more than 5.8%")
  df_othpart <- filter(df_othpart,vote_loss=="Party A lost more than 5.8%")
  
  
  ggplot() +
    geom_point(data=df,
               aes(y=mid,x=as.factor(1), col=(party))
               ,size=5) +
    geom_linerange(data=df,
                   aes(ymin=low,ymax=high,x=as.factor(1), col=(party))
                   ,size=1.5) +
    geom_point(data = df_othpart,
               aes(y=mid,x=as.factor(1), col=(party)),size=5) +
    geom_vline(xintercept = 1, size=0.3, alpha=0.3) +
    geom_hline(yintercept = 0, size=0.3, alpha=0.3, col="red") +
    ylim(c(-27,27)) + coord_flip() + facet_grid( ~ parties, switch = "y") +
    xlab("") + ylab("")  +
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.background = element_blank(),
          strip.background = element_blank(),
          # strip.text.y = element_blank(),
          axis.text.y=element_blank(),
          legend.position = "top",
          text = element_text(size=20),
          legend.title=element_blank(),
          strip.text.y = element_text(angle = 180),
          axis.ticks.y=element_blank()) +
    scale_color_grey()
  
#' ## D Robustness
#' ### D.1 Results using the log-Rile Index
#+ logrile, echo=FALSE, results='asis'
  
  # Models
  m1 <- plm(logrile ~ -1 +  logrile_lag + wlp_logrile + avg_logrile_shift_lag + countryname, 
            model = "pooling",  
            data=pd)
  
  m2 <- plm(logrile ~ -1 +  logrile_lag + wlp_logrile*pervote_diff_lag_rel  + 
              countryname +  avg_logrile_shift_lag, 
            model = "pooling",
            data=pd)
  
  pd$pervote_diff_lag_cut <-  cut(x = pd$pervote_diff_lag_rel, quantile(pd$pervote_diff_lag_rel,c(0,.33,1),na.rm=T))
  levels(pd$pervote_diff_lag_cut)  <- c("low","high")
  m3 <-    plm(logrile ~ -1 +  logrile_lag + wlp_logrile*pervote_diff_lag_cut  + countryname + avg_logrile_shift_lag, 
               model = "pooling",
               data=pd)
  
  models <- list(m1,m2,m3)
  
  robust_se <- lapply(models, double_clustered_se)
  robust_p <- lapply(models, double_clustered_se, get="Pr(>|t|)")
  

  texreg(models,  
         omit.coef=c("(countryname|party|year)"),
         override.se=robust_se,override.pvalues=robust_p
         ,custom.coef.map = list(
           'wlp_rile' =  '$W_{Losses}$ Rile',
           'wlp_logrile' =  '$W_{Losses}$ Rile',
           'wls_rile' =  '$W_{Losses}$ Rile',
           "wd_rile" = '$W_{Distance}$ Rile',
           'rile_lag' =  'Rile (t-1)',
           'logrile_lag' =  'Rile (t-1)',
           'pervote_diff_lag' = 'Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_logrile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wls_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_rile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'wlp_logrile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_logrile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'pervote_diff_lag_cutmid:wls_rile' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'pervote_diff_lag_cuthigh:wls_rile' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 25 \\%',
           'pervote_diff_lag_cutlow' = 'Vote Change (t-1) low ',
           'pervote_diff_lag_cuthigh' = 'Vote Change (t-1) high',
           'avg_rile_lag' = 'Av. Left-Right (t-1)',
           "lrs_eb_mean_shift" = "Public Opinion Shift",
           'avg_logrile_lag' = 'Av. Left-Right (t-1)',
           "median_voter_lag" = "Median voter (t-1)",
           "avg_rile_shift_lag" = "Avg. Rile Shift (t-1)",
           "median_voter_logrile_lag" = "Median voter (t-1)",
           "avg_logrile_shift_lag" = "Av. log-Rile Shift (t-1)"
         ),
         label = "tab:rob_logrile",float.pos="h",stars = c(0.1,0.05, 0.01),
         caption = "The reaction of parties to voter transtions. The table shows the results of spatial lag models estimated with OLS. The dependent variable of the model is the CMP log-rile index. Each specification includes country-fixed effects. "
         #booktabs = T, dcolumn = T,use.packages = F, scalebox = 0.9
  )
  
#' ### D.2 Controlling for Public Opinion Shifts
#+ popop, echo=FALSE, results='asis'
  

  m1 <- plm(rile ~ -1 +  rile_lag + wlp_rile 
            + countryname  + avg_rile_shift_lag + lrs_eb_mean_shift,
            model="pooling", data=pd)
  
  m2 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_rel +
              countryname  + avg_rile_shift_lag + lrs_eb_mean_shift,
            model="pooling", data=pd)
  m3 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_cut +
              countryname  + avg_rile_shift_lag + lrs_eb_mean_shift,
            model="pooling", data=pd)
  
  
  models <- list(m1,m2,m3)
  
  robust_se <- lapply(models, double_clustered_se )
  robust_p <- lapply(models, double_clustered_se, get="Pr(>|t|)")
  
  
  texreg(models,  
         omit.coef=c("(countryname|party|year)"),
         override.se=robust_se,override.pvalues=robust_p
         ,custom.coef.map = list(
           'wlp_rile' =  '$W_{Losses}$ Rile',
           'wlp_logrile' =  '$W_{Losses}$ Rile',
           'wls_rile' =  '$W_{Losses}$ Rile',
           "wd_rile" = '$W_{Distance}$ Rile',
           'rile_lag' =  'Rile (t-1)',
           'logrile_lag' =  'Rile (t-1)',
           'pervote_diff_lag' = 'Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_logrile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wls_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_rile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'wlp_logrile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_logrile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'pervote_diff_lag_cutmid:wls_rile' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'pervote_diff_lag_cuthigh:wls_rile' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 25 \\%',
           'pervote_diff_lag_cutlow' = 'Vote Change (t-1) low ',
           'pervote_diff_lag_cuthigh' = 'Vote Change (t-1) high',
           "lrs_eb_mean_shift" = "Public Opinion Shift",
           'avg_rile_lag' = 'Av. Left-Right (t-1)',
           'avg_logrile_lag' = 'Av. Left-Right (t-1)',
           "median_voter_lag" = "Median voter (t-1)",
           "avg_rile_shift_lag" = "Avg. Rile Shift (t-1)",
           "median_voter_logrile_lag" = "Median voter (t-1)"
         ),
         label = "tab:rob_eb",float.pos="h",stars = c(0.1,0.05, 0.01),
         caption = "The reaction of parties to voter transtions, controlling for public opinion shifts. The table shows the results
of spatial lag models estimated with OLS. The dependent variable of the model is
the CMP rile index. Each specification includes country-fixed effects."
         #booktabs = T, dcolumn = T,use.packages = F, scalebox = 0.9
  )
  
#' ### D.3 Controlling for Reaction to Close Parties
#+ closecomp, echo=FALSE, results='asis'
  
  m1 <- plm(rile ~ -1 +  rile_lag + wlp_rile + wd_rile 
            + countryname  + avg_rile_shift_lag ,
            model="pooling", data=pd)
  
  m2 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_rel +
              + wd_rile + countryname  + avg_rile_shift_lag ,
            model="pooling", data=pd)
  
  m3 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_cut +
              + wd_rile +  countryname  + avg_rile_shift_lag ,
            model="pooling", data=pd)
  
  m4 <- plm(rile ~ -1 +  rile_lag + wlp_rile + wngh_rile 
            + countryname  + avg_rile_shift_lag ,
            model="pooling", data=pd)
  
  m5 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_rel +
              + wngh_rile + countryname  + avg_rile_shift_lag ,
            model="pooling", data=pd)
  
  m6 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_cut +
              + wngh_rile +  countryname  + avg_rile_shift_lag ,
            model="pooling", data=pd)
  
  
  models <- list(m1,m2,m3,m4,m5,m6)
  
  robust_se <- lapply(models, double_clustered_se )
  robust_p <- lapply(models, double_clustered_se, get="Pr(>|t|)")
  
  
  texreg(models,  
         omit.coef=c("(countryname|party|year)"),
         override.se=robust_se,override.pvalues=robust_p
         ,custom.coef.map = list(
           'wlp_rile' =  '$W_{Losses}$ Rile',
           'wlp_logrile' =  '$W_{Losses}$ Rile',
           'wls_rile' =  '$W_{Losses}$ Rile',
           "wd_rile" = '$W_{Distance}$ Rile',
           "wngh_rile" = '$W_{Neighbors}$ Rile',
           'rile_lag' =  'Rile (t-1)',
           'logrile_lag' =  'Rile (t-1)',
           'pervote_diff_lag' = 'Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_logrile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wls_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_rile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'wlp_logrile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_logrile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'pervote_diff_lag_cutmid:wls_rile' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'pervote_diff_lag_cuthigh:wls_rile' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 25 \\%',
           'pervote_diff_lag_cutlow' = 'Vote Change (t-1) low ',
           'pervote_diff_lag_cuthigh' = 'Vote Change (t-1) high',
           'avg_rile_lag' = 'Av. Left-Right (t-1)',
           'avg_logrile_lag' = 'Av. Left-Right (t-1)',
           "median_voter_lag" = "Median voter (t-1)",
           "avg_rile_shift_lag" = "Avg. Rile Shift (t-1)",
           "median_voter_logrile_lag" = "Median voter (t-1)"
         ),
         label = "tab:rob_eb",float.pos="h",stars = c(0.1,0.05, 0.01),
         caption = "The reaction of parties to voter transtions, controlling for reaction to close parties. The table shows the results
of spatial lag models estimated with OLS. The dependent variable of the model is
the CMP rile index. Each specification includes country-fixed effects"
  )


#' ### D.4 Difference between Mainstream and Niche Parties
#+ niche, echo=FALSE, results='asis'
  
  # Models with rile
  m1 <- plm(rile ~ 1 +  rile_lag + wlp_rile + avg_rile_shift_lag + countryname, 
            model = "pooling",  
            data=pd[pd$niche==1,])
  m2 <- plm(rile ~ 1 +  rile_lag + wlp_rile*pervote_diff_lag_cut + avg_rile_shift_lag + countryname, 
            model = "pooling",  
            data=pd[pd$niche==1,])
  
  m3 <- plm(rile ~ 1 +  rile_lag + wlp_rile + avg_rile_shift_lag + countryname, 
            model = "pooling",  
            data=pd[pd$niche==0,])
  m4 <- plm(rile ~ 1 +  rile_lag + wlp_rile*pervote_diff_lag_cut + avg_rile_shift_lag + countryname, 
            model = "pooling",  
            data=pd[pd$niche==0,])  
  
  models <- list(m1,m2,m3,m4)
  
  robust_se <- lapply(models, double_clustered_se)
  robust_p <- lapply(models, double_clustered_se, get="Pr(>|t|)")
  
  texreg(models, 
         omit.coef=c("(countryname|party|year)"),
         override.se=robust_se,override.pvalues=robust_p,
         custom.coef.map = list(
           'wlp_rile' =  '$W_{Losses}$ Rile',
           'wlp_logrile' =  '$W_{Losses}$ Rile',
           'wls_rile' =  '$W_{Losses}$ Rile',
           "wd_rile" = '$W_{Distance}$ Rile',
           'rile_lag' =  'Rile (t-1)',
           'logrile_lag' =  'Rile (t-1)',
           'pervote_diff_lag' = 'Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_logrile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wls_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_rile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'wlp_logrile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_logrile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'pervote_diff_lag_cutmid:wls_rile' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'pervote_diff_lag_cuthigh:wls_rile' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 25 \\%',
           'pervote_diff_lag_cutlow' = 'Vote Change (t-1) low ',
           'pervote_diff_lag_cuthigh' = 'Vote Change (t-1) high',
           'avg_rile_lag' = 'Av. Left-Right (t-1)',
           'avg_logrile_lag' = 'Av. Left-Right (t-1)',
           "median_voter_lag" = "Median voter (t-1)",
           "median_voter_logrile_lag" = "Median voter (t-1)"
         ),
         label = "tab:rob4",float.pos="th",stars = c(0.005,0.05,0.01),
         caption = "The reaction of parties to voter transtions for Mainstream Parties and Niche. The table shows the results of spatial lag models estimted with OLS. 
         The dependent variable of the model is the rile index from the Party Manifesto. each specifcation includes country-fixed effects."
  )  
  
#' ### D.5 Fixed Effects Specification
#+ fe, echo=FALSE, results='asis'
  
  m1 <- plm(rile ~ -1 +  rile_lag + wlp_rile ,
            model="within", data=pd)
  
  m2 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_rel,
            model="within", data=pd)
  
  m3 <- plm(rile ~ -1 +  rile_lag + wlp_rile*pervote_diff_lag_cut,
            model="within", data=pd)
  
  models <- list(m1,m2,m3)
  
  robust_se <- lapply(models, double_clustered_se)
  robust_p <- lapply(models, double_clustered_se, get="Pr(>|t|)")
  
  texreg(models, 
         omit.coef=c("(countryname|party|year)"),
         override.se=robust_se,override.pvalues=robust_p,
         custom.coef.map = list(
           'wlp_rile' =  '$W_{Losses}$ Rile',
           'wlp_logrile' =  '$W_{Losses}$ Rile',
           'wls_rile' =  '$W_{Losses}$ Rile',
           "wd_rile" = '$W_{Distance}$ Rile',
           'rile_lag' =  'Rile (t-1)',
           'logrile_lag' =  'Rile (t-1)',
           'pervote_diff_lag' = 'Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_logrile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wls_rile:pervote_diff_lag_rel' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1)',
           'wlp_rile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_rile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'wlp_logrile:pervote_diff_lag_cutmid' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'wlp_logrile:pervote_diff_lag_cuthigh' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 66 \\%',
           'pervote_diff_lag_cutmid:wls_rile' = '$W_{Losses}$ Rile $\\times$ Vote Change (t-1) midle 50 \\%',
           'pervote_diff_lag_cuthigh:wls_rile' = '$W_{Losses}$ Rile $\\times$ \\\\ Vote Change (t-1) highest 25 \\%',
           'pervote_diff_lag_cutlow' = 'Vote Change (t-1) low ',
           'pervote_diff_lag_cuthigh' = 'Vote Change (t-1) high',
           'avg_rile_lag' = 'Av. Left-Right (t-1)',
           'avg_logrile_lag' = 'Av. Left-Right (t-1)',
           "median_voter_lag" = "Median voter (t-1)",
           "median_voter_logrile_lag" = "Median voter (t-1)"
         ),
         label = "tab:rob4",float.pos="th",stars = c(0.005,0.05,0.01),
         caption = "The reaction of parties to voter transtions, including party fixed effects. The table shows the results
of spatial lag models estimated with OLS. The dependent variable of the model is
the CMP rile index. Each specification includes country-fixed effects"
  )
  